import React, { useState, useEffect, useRef } from 'react';
import {
    Box,
    Container,
    Typography,
    Grid,
    Card,
    CardContent,
    CardMedia,
    CardActions,
    Button,
    IconButton,
    TextField,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    CircularProgress,
    Chip,
    Divider,
    Paper,
    InputAdornment,
    Snackbar,
    Alert,
    Tooltip
} from '@mui/material';
import {
    Search as SearchIcon,
    Add as AddIcon,
    Download as DownloadIcon,
    Visibility as VisibilityIcon,
    Delete as DeleteIcon,
    CloudUpload as CloudUploadIcon,
    FilterList as FilterListIcon,
    Edit as EditIcon
} from '@mui/icons-material';
import fileService from '../services/fileService';
import modelService from '../services/modelService';
import { useNavigate } from 'react-router-dom';

// 材料库组件
const MaterialLibrary = () => {
    // 状态管理
    const [materials, setMaterials] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [uploadDialogOpen, setUploadDialogOpen] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(false);
    const [selectedFile, setSelectedFile] = useState(null);
    const [materialName, setMaterialName] = useState('');
    const [materialDescription, setMaterialDescription] = useState('');
    const [notification, setNotification] = useState({ open: false, message: '', severity: 'info' });

    // 文件上传引用
    const fileInputRef = useRef(null);

    // 导航引用
    const navigate = useNavigate();

    // 模拟材料数据 - 实际项目中应从API获取
    useEffect(() => {
        // 模拟加载数据
        setTimeout(() => {
            const mockMaterials = [
                {
                    id: '1',
                    name: '金属材质',
                    description: '适用于金属、钢铁、铝材等物体表面',
                    type: 'metal',
                    thumbnail: 'https://img.freepik.com/free-photo/metal-texture-background_53876-94035.jpg?size=626&ext=jpg',
                    format: 'mtl'
                },
                {
                    id: '2',
                    name: '木材材质',
                    description: '适用于各种木材表面纹理',
                    type: 'wood',
                    thumbnail: 'https://img.freepik.com/free-photo/wood-texture-background_93675-129415.jpg?size=626&ext=jpg',
                    format: 'mtl'
                },
                {
                    id: '3',
                    name: '塑料材质',
                    description: '适用于塑料、橡胶等材质',
                    type: 'plastic',
                    thumbnail: 'https://img.freepik.com/free-photo/black-texture_1160-716.jpg?size=626&ext=jpg',
                    format: 'mtl'
                },
                {
                    id: '4',
                    name: '大理石材质',
                    description: '适用于大理石、石材等表面',
                    type: 'marble',
                    thumbnail: 'https://img.freepik.com/free-photo/white-marble-texture-background_53876-88173.jpg?size=626&ext=jpg',
                    format: 'mtl'
                },
                {
                    id: '5',
                    name: '玻璃材质',
                    description: '透明、半透明玻璃材质',
                    type: 'glass',
                    thumbnail: 'https://img.freepik.com/free-photo/transparent-glass-texture-window-reflection_53876-128269.jpg?size=626&ext=jpg',
                    format: 'mtl'
                }
            ];

            setMaterials(mockMaterials);
            setLoading(false);
        }, 1000);
    }, []);

    // 处理材料上传
    const handleFileUpload = (event) => {
        const file = event.target.files[0];
        if (!file) return;

        // 自动设置材料名称（基于文件名）
        const baseName = file.name.split('.')[0];
        setMaterialName(baseName);
        setSelectedFile(file);

        // 打开上传对话框
        setUploadDialogOpen(true);

        // 重置文件输入，允许重新选择相同文件
        event.target.value = '';
    };

    // 上传材料到服务器
    const uploadMaterial = async () => {
        if (!selectedFile || !materialName) {
            showNotification('请提供所有必需信息', 'warning');
            return;
        }

        try {
            setUploadProgress(true);

            // 模拟上传延迟
            await new Promise(resolve => setTimeout(resolve, 1500));

            // 模拟成功上传
            const newMaterial = {
                id: `material-${Date.now()}`,
                name: materialName,
                description: materialDescription || `导入的${selectedFile.name.split('.').pop().toUpperCase()}材料`,
                type: 'custom',
                format: selectedFile.name.split('.').pop().toLowerCase(),
                createdAt: new Date().toISOString()
            };

            // 添加到材料列表
            setMaterials([newMaterial, ...materials]);

            // 显示成功通知
            showNotification('材料上传成功', 'success');
            setUploadDialogOpen(false);

            // 重置表单
            setSelectedFile(null);
            setMaterialName('');
            setMaterialDescription('');

        } catch (error) {
            console.error('上传材料失败:', error);
            showNotification('上传材料失败: ' + (error.message || '未知错误'), 'error');
        } finally {
            setUploadProgress(false);
        }
    };

    // 下载材料
    const downloadMaterial = async (materialId) => {
        try {
            setLoading(true);

            // 模拟下载延迟
            await new Promise(resolve => setTimeout(resolve, 800));

            // 模拟下载成功
            showNotification('材料下载成功', 'success');
        } catch (error) {
            console.error('下载材料失败:', error);
            showNotification('下载材料失败', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 删除材料
    const deleteMaterial = async (materialId) => {
        if (!window.confirm('确定要删除这个材料吗？此操作不可撤销。')) {
            return;
        }

        try {
            setLoading(true);

            // 模拟删除延迟
            await new Promise(resolve => setTimeout(resolve, 500));

            // 从列表中移除
            setMaterials(materials.filter(material => material.id !== materialId));
            showNotification('材料删除成功', 'success');
        } catch (error) {
            console.error('删除材料失败:', error);
            showNotification('删除材料失败', 'error');
        } finally {
            setLoading(false);
        }
    };

    // 显示通知
    const showNotification = (message, severity = 'info') => {
        setNotification({
            open: true,
            message,
            severity
        });
    };

    // 处理通知关闭
    const handleNotificationClose = () => {
        setNotification({ ...notification, open: false });
    };

    // 过滤材料
    const filteredMaterials = materials.filter(material =>
        material.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (material.description && material.description.toLowerCase().includes(searchTerm.toLowerCase())) ||
        (material.type && material.type.toLowerCase().includes(searchTerm.toLowerCase()))
    );

    // 导入到编辑器
    const importToEditor = (material) => {
        try {
            // 将材料信息存储在sessionStorage中，供编辑器读取
            sessionStorage.setItem('importedMaterial', JSON.stringify(material));

            // 显示通知
            showNotification('材料已准备好导入到编辑器', 'success');

            // 导航到编辑器页面
            setTimeout(() => {
                navigate('/models/geometry/create');
            }, 1000);
        } catch (error) {
            console.error('准备导入材料时出错:', error);
            showNotification('准备导入材料失败', 'error');
        }
    };

    return (
        <Container maxWidth="lg" sx={{ mt: 4, mb: 8 }}>
            <Paper elevation={3} sx={{ p: 3, borderRadius: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                    <Typography variant="h4" component="h1" gutterBottom>
                        材料库
                    </Typography>

                    <Box>
                        <Button
                            variant="contained"
                            color="primary"
                            startIcon={<CloudUploadIcon />}
                            onClick={() => fileInputRef.current.click()}
                            sx={{ mr: 1 }}
                        >
                            上传材料
                        </Button>
                        <input
                            type="file"
                            ref={fileInputRef}
                            onChange={handleFileUpload}
                            style={{ display: 'none' }}
                            accept=".mtl,.jpg,.png,.jpeg"
                        />
                    </Box>
                </Box>

                <Box sx={{ mb: 3 }}>
                    <TextField
                        fullWidth
                        placeholder="搜索材料..."
                        variant="outlined"
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        InputProps={{
                            startAdornment: (
                                <InputAdornment position="start">
                                    <SearchIcon />
                                </InputAdornment>
                            ),
                        }}
                        size="small"
                    />
                </Box>

                <Divider sx={{ mb: 3 }} />

                {loading ? (
                    <Box sx={{ display: 'flex', justifyContent: 'center', py: 5 }}>
                        <CircularProgress />
                    </Box>
                ) : (
                    <>
                        <Typography variant="subtitle1" sx={{ mb: 2 }}>
                            {filteredMaterials.length > 0
                                ? `共找到 ${filteredMaterials.length} 个材料`
                                : '暂无材料'}
                        </Typography>

                        <Grid container spacing={3}>
                            {filteredMaterials.map((material) => (
                                <Grid item xs={12} sm={6} md={4} key={material.id}>
                                    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                                        <CardMedia
                                            component="div"
                                            sx={{
                                                height: 180,
                                                bgcolor: '#f0f0f0',
                                                display: 'flex',
                                                alignItems: 'center',
                                                justifyContent: 'center',
                                                backgroundImage: material.thumbnail ? `url(${material.thumbnail})` : 'none',
                                                backgroundSize: 'cover',
                                                backgroundPosition: 'center'
                                            }}
                                        >
                                            {!material.thumbnail && (
                                                <Box sx={{ textAlign: 'center' }}>
                                                    <Typography variant="body2" color="text.secondary">
                                                        {material.type ? `${material.type} 材料` : '标准材料'}
                                                    </Typography>
                                                </Box>
                                            )}
                                        </CardMedia>

                                        <CardContent sx={{ flexGrow: 1 }}>
                                            <Typography variant="h6" gutterBottom noWrap>
                                                {material.name}
                                            </Typography>

                                            <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
                                                {material.description || '无描述'}
                                            </Typography>

                                            <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5, mt: 1 }}>
                                                <Chip
                                                    label={material.type || 'standard'}
                                                    size="small"
                                                    color="primary"
                                                    variant="outlined"
                                                />
                                                {material.format && (
                                                    <Chip
                                                        label={material.format.toUpperCase()}
                                                        size="small"
                                                        color="secondary"
                                                        variant="outlined"
                                                    />
                                                )}
                                            </Box>
                                        </CardContent>

                                        <CardActions sx={{ justifyContent: 'space-between', px: 2, pb: 2 }}>
                                            <Box>
                                                <Tooltip title="预览材料">
                                                    <IconButton
                                                        color="primary"
                                                        onClick={() => alert(`预览材料: ${material.name}`)}
                                                    >
                                                        <VisibilityIcon />
                                                    </IconButton>
                                                </Tooltip>

                                                <Tooltip title="下载材料">
                                                    <IconButton
                                                        color="primary"
                                                        onClick={() => downloadMaterial(material.id)}
                                                    >
                                                        <DownloadIcon />
                                                    </IconButton>
                                                </Tooltip>

                                                <Tooltip title="导入到编辑器">
                                                    <IconButton
                                                        color="secondary"
                                                        onClick={() => importToEditor(material)}
                                                    >
                                                        <EditIcon />
                                                    </IconButton>
                                                </Tooltip>
                                            </Box>

                                            <Tooltip title="删除材料">
                                                <IconButton
                                                    color="error"
                                                    onClick={() => deleteMaterial(material.id)}
                                                >
                                                    <DeleteIcon />
                                                </IconButton>
                                            </Tooltip>
                                        </CardActions>
                                    </Card>
                                </Grid>
                            ))}
                        </Grid>

                        {filteredMaterials.length === 0 && !loading && (
                            <Box sx={{ textAlign: 'center', py: 5 }}>
                                <Typography variant="body1" color="text.secondary">
                                    未找到匹配的材料
                                </Typography>
                                <Button
                                    variant="outlined"
                                    startIcon={<AddIcon />}
                                    onClick={() => fileInputRef.current.click()}
                                    sx={{ mt: 2 }}
                                >
                                    上传新材料
                                </Button>
                            </Box>
                        )}
                    </>
                )}
            </Paper>

            {/* 上传对话框 */}
            <Dialog
                open={uploadDialogOpen}
                onClose={() => !uploadProgress && setUploadDialogOpen(false)}
                maxWidth="sm"
                fullWidth
            >
                <DialogTitle>上传材料</DialogTitle>
                <DialogContent>
                    <Box sx={{ mb: 2 }}>
                        <Typography variant="body2" color="text.secondary" gutterBottom>
                            已选择文件: {selectedFile?.name || '未选择文件'}
                        </Typography>
                        {selectedFile && (
                            <Chip
                                label={selectedFile.name.split('.').pop().toUpperCase()}
                                color="primary"
                                size="small"
                                sx={{ mr: 1 }}
                            />
                        )}
                    </Box>

                    <TextField
                        autoFocus
                        margin="dense"
                        label="材料名称"
                        fullWidth
                        variant="outlined"
                        value={materialName}
                        onChange={(e) => setMaterialName(e.target.value)}
                        required
                        disabled={uploadProgress}
                        sx={{ mb: 2 }}
                    />

                    <TextField
                        margin="dense"
                        label="材料描述"
                        fullWidth
                        variant="outlined"
                        value={materialDescription}
                        onChange={(e) => setMaterialDescription(e.target.value)}
                        multiline
                        rows={3}
                        disabled={uploadProgress}
                    />
                </DialogContent>

                <DialogActions sx={{ px: 3, pb: 3 }}>
                    <Button
                        onClick={() => setUploadDialogOpen(false)}
                        disabled={uploadProgress}
                    >
                        取消
                    </Button>
                    <Button
                        variant="contained"
                        onClick={uploadMaterial}
                        disabled={uploadProgress || !selectedFile || !materialName}
                        startIcon={uploadProgress ? <CircularProgress size={20} /> : <CloudUploadIcon />}
                    >
                        {uploadProgress ? '上传中...' : '上传'}
                    </Button>
                </DialogActions>
            </Dialog>

            {/* 通知消息 */}
            <Snackbar
                open={notification.open}
                autoHideDuration={5000}
                onClose={handleNotificationClose}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            >
                <Alert
                    onClose={handleNotificationClose}
                    severity={notification.severity}
                    variant="filled"
                >
                    {notification.message}
                </Alert>
            </Snackbar>
        </Container>
    );
};

export default MaterialLibrary; 